package common.util;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.yuntsg.ruiijn.databse_search.entity.FileDetails;
import com.yuntsg.ruiijn.databse_search.mapper.FileDetailsMapper;
import common.vo.CompareImgVo;
import common.vo.WorkNoUidVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@Component
@SuppressWarnings("all")
@Slf4j

public class NacosUtil {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private FileDetailsMapper fileDetailsMapper;
    @Value("${central.server-name.feature}")
    private String centralServerNameFeature;
    @Value("${central.server-name.classify}")
    private String centralServerNameClassify;
    @Value("${central.server-name.opencv}")
    private String centralServerNameOpencv;
    @Value("${minio.bucketName}")
    private String bucketName;
    @NacosInjected
    private NamingService namingService;


    public List<FileDetails> workNoUid(String path, Integer fid, Integer rid, Integer source, Integer uid) throws Exception {
        List<FileDetails> fileDetailsList = new ArrayList<>();
        Instance nacos = namingService.selectOneHealthyInstance(centralServerNameOpencv, "DEFAULT_GROUP");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        WorkNoUidVo build = WorkNoUidVo.builder().path(path.replace("oss/", "")).rid(rid).uid(uid).source(source).fid(fid).build();
        String url = StrUtil.format("http://{}:{}/provider/workNoUid", nacos.getIp(), nacos.getPort());
        FileDetails[] fileDetails = restTemplate.postForObject(url, new HttpEntity<>(JSONObject.toJSONString(build), headers), FileDetails[].class);
        if (null != fileDetails && fileDetails.length > 0) {
            fileDetailsList = Arrays.asList(fileDetails);
        }
        return fileDetailsList;
    }

    public List<FileDetails> workfiligreeNoId(String path, Integer fid, Integer rid, Integer source, Integer uid) throws Exception {
        List<FileDetails> fileDetailsList = new ArrayList<>();
        Instance nacos = namingService.selectOneHealthyInstance(centralServerNameOpencv, "DEFAULT_GROUP");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        WorkNoUidVo build = WorkNoUidVo.builder().path(path.replace("oss/", "")).rid(rid).uid(uid).source(source).fid(fid).build();
        String url = StrUtil.format("http://{}:{}/provider/workfiligreeNoId", nacos.getIp(), nacos.getPort());
        FileDetails[] fileDetails = restTemplate.postForObject(url, new HttpEntity<>(JSONObject.toJSONString(build), headers), FileDetails[].class);
        if (null != fileDetails && fileDetails.length > 0) {
            fileDetailsList = Arrays.asList(fileDetails);
        }
        return fileDetailsList;
    }

    public SortUtil.Result compareImg(String imgFile1, JSONArray box1, String imgFile2, JSONArray box2) throws Exception {
        Instance instance = namingService.selectOneHealthyInstance("compare_server", "DEFAULT_GROUP");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        CompareImgVo build = CompareImgVo.builder().imgFile2(imgFile2.replace("oss/", "")).imgFile1(imgFile1.replace("oss/", "")).build();
        Map<String, Object> vo = new HashMap<>();
        vo.put("img1", imgFile1.replace("oss/", ""));
        vo.put("box1", box1);
        vo.put("img2", imgFile2.replace("oss/", ""));
        vo.put("box2", box2);
        String url = StrUtil.format("http://{}:{}/compare", instance.getIp(), instance.getPort());
        JSONObject jsonObject = restTemplate.postForObject(url, new HttpEntity<>(new JSONObject(vo).toJSONString(), headers), JSONObject.class);
        SortUtil.Result result = jsonObject.toJavaObject(SortUtil.Result.class);
        jsonObject.put("resultImg", "");
        fileDetailsMapper.insertResultRecord(imgFile1.replace("oss/", ""), imgFile2.replace("oss/", ""), jsonObject.toJSONString(), jsonObject.getInteger("allResult"));
        return result;
    }


    public List<Float> imageFeature(String path) throws Exception {
        Instance instance = namingService.selectOneHealthyInstance(centralServerNameFeature, "DEFAULT_GROUP");
        String url = StrUtil.format("http://{}:{}/detailsminio/{}/", instance.getIp(), instance.getPort(), bucketName);

        JSONObject u = restTemplate.getForObject(url + path.replace("oss/", ""), JSONObject.class);
        if (u.getInteger("code").equals(200)) {
            String data = u.getString("data");
            return JSON.parseArray(data, Float.class);
        }
        return new ArrayList<Float>();

    }


    public Integer imageClassify(String path) throws Exception {
        Instance instance = namingService.selectOneHealthyInstance(centralServerNameClassify, "DEFAULT_GROUP");
        String url = StrUtil.format("http://{}:{}/detailsminio/{}/", instance.getIp(), instance.getPort(), bucketName);
        JSONObject u = restTemplate.getForObject(url + path.replace("oss/", ""), JSONObject.class);
        if (u.getInteger("code").equals(200)) {
            String data = u.getString("data");
            return data.equals("picture") ? 4 : 5;
        }
        return 0;
    }

    public Integer imageClassifyStep(String path) throws Exception {
        Instance instance = namingService.selectOneHealthyInstance(centralServerNameClassify, "DEFAULT_GROUP");
        String url = StrUtil.format("http://{}:{}/detailsminioStep/{}/", instance.getIp(), instance.getPort(), bucketName);
        JSONObject u = restTemplate.getForObject(url + path.replace("oss/", ""), JSONObject.class);
        if (u.getInteger("code").equals(200)) {
            String data = u.getString("data");
            return data.equals("picture") ? 0 : -1;
        }
        return 0;
    }

    public JSONArray numIdentify(String path) {
        Instance instance = null;
        try {
            instance = namingService.selectOneHealthyInstance("numIdentify_server", "DEFAULT_GROUP");
        } catch (NacosException e) {
            log.error("numIdentify_server 获取失败");
            return new JSONArray();
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("img", path.replace("oss/", ""));
        String url = StrUtil.format("http://{}:{}/numIdentify", instance.getIp(), instance.getPort());
        JSONObject res = restTemplate.postForObject(url, new HttpEntity<>(jsonObject.toJSONString(), headers), JSONObject.class);
        if (res.getInteger("flag") == 1) {
            return res.getJSONArray("data");
        }
        return new JSONArray();
    }
}
